package com.guochu.common.dbconnect;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.lang.Nullable;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: luc
 * @Date: 2019-9-25 14:50
 */
public class DynamicDataSource extends AbstractRoutingDataSource {

    @Nullable
    private Map<Object, Object> targetDataSources;
    @Nullable
    private Object defaultTargetDataSource;
    private boolean lenientFallback = true;
    @Nullable
    private Map<Object, DataSource> resolvedDataSources;
    @Nullable
    private DataSource resolvedDefaultDataSource;

    @Override
    public void setTargetDataSources(Map<Object, Object> targetDataSources) {
        this.targetDataSources = targetDataSources;
    }

    @Override
    public void setDefaultTargetDataSource(Object defaultTargetDataSource) {
        this.defaultTargetDataSource = defaultTargetDataSource;
    }

    @Override
    public void afterPropertiesSet() {
        if (this.targetDataSources == null) {
            throw new IllegalArgumentException("Property 'targetDataSources' is required");
        } else {
            this.resolvedDataSources = new HashMap(this.targetDataSources.size());
            this.targetDataSources.forEach((key, value) -> {
                Object lookupKey = this.resolveSpecifiedLookupKey(key);
                DataSource dataSource = this.resolveSpecifiedDataSource(value);
                this.resolvedDataSources.put(lookupKey, dataSource);
            });
            if (this.defaultTargetDataSource != null) {
                this.resolvedDefaultDataSource = this.resolveSpecifiedDataSource(this.defaultTargetDataSource);
            }
        }
    }

    @Override
    public void setLenientFallback(boolean lenientFallback) {
        this.lenientFallback = lenientFallback;
    }

    @Override
    protected DataSource determineTargetDataSource() {
        DataSource dataSource;
        DatabaseInfo databaseInfo = DatabaseContextHolder.getDatabaseInfo();

        if (databaseInfo != null&&databaseInfo.getDatabaseType()==DatabaseType.autodb){
            DruidDataSource druidDataSource = (DruidDataSource)this.resolvedDataSources.get(databaseInfo.getDatabaseType());
            druidDataSource.setUrl(databaseInfo.getUrl());
            druidDataSource.setPassword(databaseInfo.getPassword());
            druidDataSource.setUsername(databaseInfo.getUsername());
            dataSource=druidDataSource;
        }else{
            dataSource = this.resolvedDefaultDataSource;
        }

        if (dataSource == null) {
            throw new IllegalStateException("缺少数据源");
        } else {
            return dataSource;
        }
    }

    @Override
    protected Object determineCurrentLookupKey() {
        return "";
    }
}
